﻿namespace Filters.Demo
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Windows.Forms;
    using Filters.Demo.Core;
    using Filters.Demo.Core.FilterConfiguration;
    using WeifenLuo.WinFormsUI;

    public partial class FiltersForm : Content
    {
        private readonly IHost host;
        private IList<FilterElement> filters;

        public FiltersForm(IHost host)
        {
            this.InitializeComponent();

            this.host = host;
        }

        public void UpdateFiltersList(IList<FilterElement> filters)
        {
            this.filtersList.Items.Clear();
            this.filtersList.Items.AddRange(filters.ToArray());

            this.filters = filters;
        }

        private void FiltersFormFormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            if (e.CloseReason != System.Windows.Forms.CloseReason.ApplicationExitCall)
            {
                this.Hide();
                e.Cancel = true;
            }
        }

        private void SaveFiltersButtonClick(object sender, EventArgs e)
        {
            this.saveFileDialog.FileName = "filters.xml";
            this.saveFileDialog.FilterIndex = 0;

            // show dialog
            if (this.saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                var configuration = new ConfigurationBuilder(this.saveFileDialog.FileName);

                configuration.SaveFiltersConfiguration(this.filters);
            }
        }

        private FiltersConfiguration GetFiltersConfiguration()
        {
            return new FiltersConfiguration
                                    {
                                        Filters = new Collection<FilterElement>(this.filters)
                                    };
        }

        private void OpenFiltersListButtonClick(object sender, EventArgs e)
        {
            this.openFileDialog.FilterIndex = 0;
            this.openFileDialog.FileName = "filters.xml";

            if (this.openFileDialog.ShowDialog() == DialogResult.OK)
            {
                IFilterApplierEngine filterEngine = new FilterApplierEngine(this.host.CurrentImageFilter);

                filterEngine.ApplyFilters(this.openFileDialog.FileName);
            }
        }
    }
}
